package com.kaesar.leetcode.LeetCode_001_050;

import java.util.*;

public class LeetCode_049 {
    public static List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> tempResult = new HashMap<>();
        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String sortedStr = String.valueOf(chars);
            if (tempResult.get(sortedStr) == null) {
                List<String> values = new ArrayList<>();
                values.add(str);
                tempResult.put(sortedStr, values);
            } else {
                tempResult.get(sortedStr).add(str);
            }
        }
        List<List<String>> result = new ArrayList<>();
        result.addAll(tempResult.values());
        return result;
    }

    public static void main(String[] args) {
        String[] strs = new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> lists = groupAnagrams(strs);
        for (List<String> list : lists) {
            for (String s : list) {
                System.out.print(s + " ");
            }
            System.out.println();
        }
    }
}
